package com.bobo.gmall.realtime.app.ods;

import com.alibaba.ververica.cdc.connectors.mysql.MySQLSource;
import com.alibaba.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.alibaba.ververica.cdc.debezium.DebeziumSourceFunction;
import com.bobo.gmall.realtime.app.function.CustomerDeserialization;
import com.bobo.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class FlinkCDC {

    public static void main(String[] args) throws Exception {
        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //1.1 开启checkpoint，并指定状态后端为FS         memory fs rocksdb
//        env.setStateBackend(new FsStateBackend("hdfs://192.168.45.132:9000/gmall-flink/ck"));
//        env.enableCheckpointing(5000L);   // 即5s触发一次checkPoint
//        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);  // 模式
//        env.getCheckpointConfig().setAlignmentTimeout(10000L);   // 超时时间 10s
//        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);    //
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000);   // 两次checkpoint间最小间隔时间
//        //env.setRestartStrategy(RestartStrategies.fixedDelayRestart());  老版本需要注意

        //2.通过FlinkCDC构建SourceFunction并读取数据
        DebeziumSourceFunction<String> sourceFunction = MySQLSource.<String>builder()
                .hostname("192.168.45.132")
                .port(3306)
                .username("root")
                .password("123456")
                .databaseList("gmall_flink")
//                .tableList("gmall_flink.base_trademark")   //如果不添加该参数，则消费指定数据库中所有表的数据，如果指定，指定方式为db.table
                .deserializer(new CustomerDeserialization())
//                .debeziumProperties()
                .startupOptions(StartupOptions.initial())   //initial(): 无checkPoint时，都是从头开始读;    latest(): 直接读最新的数据
                .build();

        DataStreamSource<String> streamSource = env.addSource(sourceFunction);

        //3.打印数据，并将数据写入Kafka
        streamSource.print();
        String sinkTopic = "ods_base_db";
        streamSource.addSink(MyKafkaUtil.getKafkaProducer(sinkTopic));

        //4.启动任务
        env.execute("FlinkCDC");

    }
}
